package com.course.servlet;

import com.course.entity.Student;
import com.course.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/xuesheng_edit_student")
public class XueshengEditStudentServlet extends HttpServlet {
    private final StudentService studentService = new StudentService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            try {
                int id = Integer.parseInt(idStr);
                Student student = studentService.findById(id);
                if (student != null) {
                    request.setAttribute("student", student);
                    request.getRequestDispatcher("/WEB-INF/jsp/xuesheng_edit_student.jsp").forward(request, response);
                } else {
                    response.sendRedirect(request.getContextPath() + "/guanliyuan_student_manage"); // Student not found
                }
            } catch (NumberFormatException e) {
                response.sendRedirect(request.getContextPath() + "/guanliyuan_student_manage"); // Invalid ID
            }
        } else {
            response.sendRedirect(request.getContextPath() + "/guanliyuan_student_manage"); // No ID parameter
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        int id = Integer.parseInt(request.getParameter("id"));
        String studentId = request.getParameter("studentId");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String className = request.getParameter("className");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");

        Student student = new Student();
        student.setId(id);
        student.setStudentId(studentId);
        student.setUsername(username);
        student.setPassword(password);
        student.setName(name);
        student.setGender(gender);
        student.setClassName(className);
        student.setEmail(email);
        student.setPhone(phone);

        studentService.updateStudent(student);

        response.sendRedirect(request.getContextPath() + "/guanliyuan_student_manage");
    }
} 